﻿using System;
using System.Text.RegularExpressions;

namespace ToyundaPhone.Helpers
{
	public class NameCleaningRowFilter : ToyundaPhone.FileFormat.IRowGenerator
	{
		private static readonly Regex extension = new Regex(@"\.[A-Z0-9]{3}$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
		private static readonly Regex missplacedKindSpecifier = new Regex(@" - ([A-Z][A-Z0-9]+(?: [A-Z][A-Z0-9]+){0,2}) - ", RegexOptions.Compiled);
		private readonly ToyundaPhone.FileFormat.IRowGenerator source;

		public NameCleaningRowFilter(ToyundaPhone.FileFormat.IRowGenerator source)
		{
			this.source = source;
		}

		#region IRowGenerator Members

		public object[] GetNextRow()
		{
			object[] row = source.GetNextRow();
			if ((row != null) && (row[1] is string) && ((row[2] == null) || (row[2] is string)))
			{
				Match m;
				// Remove file extension.
				m = extension.Match((string)((row[2] != null) ? row[2] : row[1]));
				if (m.Success)
				{
					if (row[2] != null)
					{
						row[2] = ((string)row[2]).Substring(0, m.Groups[0].Index);
					}
					else
					{
						row[1] = ((string)row[1]).Substring(0, m.Groups[0].Index);
					}
				}
				// Missplaced kind specifier.
				if (row[2] != null)
				{
					m = missplacedKindSpecifier.Match((string)row[2]);
					if (m.Success)
					{
						row[1] = (string)row[1] + " - " + ((string)row[2]).Substring(0, m.Groups[0].Index);
						row[2] = ((string)row[2]).Substring(m.Groups[1].Index);
					}
				}
			}
			return row;
		}

		#endregion
	}
}
